﻿using Microsoft.Extensions.DependencyInjection;

namespace Amber.Arch.Catty
{
    public class CatServiceProviderFactory : IServiceProviderFactory<CatBuilder>
    {
        public CatBuilder CreateBuilder(IServiceCollection services)
        {
            Cat cat = new();
            foreach (var service in services)
            {
                if (service.ImplementationFactory is not null)
                {
                    cat.Register(service.ServiceType, provider => service.ImplementationFactory(provider), service.Lifetime.AsCatLifeTime());
                }
                else if (service.ImplementationInstance is not null)
                {
                    cat.Register(service.ServiceType, service.ImplementationInstance);
                }
                else
                {
                    cat.Register(service.ServiceType, service.ImplementationType, service.Lifetime.AsCatLifeTime());
                }
            }
            return new CatBuilder(cat);
        }

        public IServiceProvider CreateServiceProvider(CatBuilder containerBuilder)
            => containerBuilder.BuildServiceProvider();
    }
}
